package com.teewe.utils
{
	import com.teewe.model.data.ID;
	import com.teewe.model.data.Timeline;
	
	import flash.utils.*;
	
	public class Utils
	{
		public static function formatDate (date:Date, formatString:String="YYYY/MM/DD HH:JJ"):String
		{
			if (formatString.indexOf("YYYY") != -1)
				formatString = formatString.replace("YYYY", date.fullYear);
			else
				formatString = formatString.replace("YY", date.fullYear.toString().slice(2));
				
			formatString = formatString.replace("MM", addLeadingZeroSimple(date.month)); 
			formatString = formatString.replace("DD", addLeadingZeroSimple(date.date)); 
			formatString = formatString.replace("HH", addLeadingZeroSimple(date.hours)); 
			formatString = formatString.replace("JJ", addLeadingZeroSimple(date.minutes)); 
			return formatString;
		}
		
		public static function addLeadingZeroSimple (value:int):String
		{
			if (value < 10 && value > -1)
				return "0" + value;
				
			return value.toString();
		}
		
		public static function addLeadingChars (value:int, mask:String="0000"):String
		{
			var valueString:String = value.toString();
			
			if (valueString.length >= mask.length)
				return valueString;
				
			return mask.substr(0, mask.length - valueString.length) + valueString;
		}
		
		public static function mergeTimelineToArray (timeline:Timeline, ...assetLists:Array /* Array */):Array
		{
			var result:Array = [];
			
			if (timeline.length == 0)
				return result;
				
			var temp:Array = []; /* ID */
			var list:Array; /* ID */
			for each (list in assetLists)
				temp = temp.concat(list);
				
			if (temp.length == 0)
				return result;
			
			var id:ID;
			var item:ID;
			for each (id in timeline)
			{
				item = getElementById(id, temp, true);
				result.push(item);		
			}
					
			return result;
		}
		
		public static function getElementById (id:ID, list:Array /* ID */, deleteFoundItem:Boolean=false):ID
		{
			var item:ID;
			var i:int;
			var len:int = list.length;
			for (i=0; i < len; i++)
			{
				item = list[i];
				if (item.equals(id))
				{
					if (deleteFoundItem == true)
						list.splice(i, 1);
						
					return item;
				}
			}
			
			return null;
		}
	}
}